// 数字字典
import { defineStore } from 'pinia'

const state = () => ({
  // 行政区划
  areaDict: [],
})

const getters = {
  areaDictGet: (state: any) => {
    let key = 'areaDict'
    let code = 'gzDistrict'

    if (state[key].length) {
      return (IsReGet: any) => IsReGet && state.getDict({ key, code })
    }
    state.getDict({ key, code })
  },
}

const actions = {
  // 设置 State
  setState({ key, value }: { key: S; value: any }) {
    this[key] = value
  },

  // 获取列表 数字字典（异步获取会返回promise，在组件中使用需await）
  getDict({ key, code }: { key: S; code: S }) {
    let { $http } = window

    $http({
      url: 'dictionary.list',
      params: { pageNum: 1, pageSize: 999999 },
      data: { code },
    }).then((res: any) => {
      this[key] = res.data.list
    })
  },
}

// 匹配数字字典
function dictMatch({
  key = 'key',
  value,
  data,
}: {
  key?: S
  value: any
  data?: any
}) {
  if (!value && value !== 0) return

  let state = window.$store.dictionary
  let res = ''
  let valueList = typeof value === 'object' ? value : [value]
  let list: any = []

  if (data) list = data
  else if (state[key]) list = state[key]

  valueList.forEach((item: any, i: N) => {
    const one = list.find((items: any) => {
      if (data) return items[key || 'key'] === item
      return items.key === item
    })
    if (!one) return ''
    res += i ? '、' + one.value : one.value
  })
  return res
}
async function dictMatchAsync({
  key = 'key',
  value,
  data,
}: {
  key?: S
  value: any
  data?: any
}) {
  if (!value && value !== 0) return

  let state = window.$store.dictionary
  let res = ''
  let valueList = typeof value === 'object' ? value : [value]
  let list: any = []

  if (data) list = data
  else if (state[key]) list = state[key]
  else {
    await state[key + 'Get']()
    list = state[key]
  }

  valueList.forEach((item: any, i: N) => {
    const one = list.find((items: any) => {
      if (data) return items[key || 'key'] === item
      return items.key === item
    })
    if (!one) return ''
    res += i ? '、' + one.value : one.value
  })
  return res
}
window.$dictMatch = dictMatch
window.$dictMatchAsync = dictMatchAsync

export const useStore = (id: S) =>
  defineStore({ id, state, getters, actions })()
